<!-- 
<template>
  <div class="modal-overlay" v-if="visible" @click.self="closeModal">
    <div class="modal-container">
      
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'upload-success']);

const fileInput = ref(null);
const dragOver = ref(false);
const previewImage = ref(null);
const selectedFile = ref(null);
const uploadProgress = ref(0);

const closeModal = () => {
  props.visible
  emit('update:visible', false);
  resetState();
};

const resetState = () => {
  dragOver.value = false;
  previewImage.value = null;
  selectedFile.value = null;
  uploadProgress.value = 0;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
</style>

 -->
 <template>
  <div class="modal-overlay" v-if="visible" @click.self="closeModal">
    <div class="modal-container">
      <div class="modal-header">
        <h3>富文本编辑器</h3>
        <button class="close-btn" @click="closeModal">&times;</button>
      </div>
      <div class="modal-header row">
        <span>标题：</span>
        <input type="text" v-model="article.title" placeholder="请输入标题" >
      </div>
      <div class="modal-header row">
        <span>图片：{{ article.picture }}</span>
        <button @click="showModal = true">上传图片</button>
        <FileForm 
          v-model:visible="showModal"
          @upload-success="handleUploadSuccess"
        />
      </div>
      <div class="modal-content">
        <QuillEditor
          ref="quillEditor"
          v-model:content="content"
          contentType="html"
          :options="editorOptions"
          theme="snow"
          @ready="onEditorReady"
        />
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="closeModal">取消</button>
        <button class="confirm-btn" @click="handleConfirm">确认</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, defineEmits, defineProps } from 'vue';
import { QuillEditor } from '@vueup/vue-quill';
import { userCreateArt } from '@/api/BlogUser';
import { articleDetail } from '@/api/BlogVisit';
import { userUpdateArt } from '@/api/BlogUser';
import FileForm from '@/components/FileForm.vue';
import server from '@/api/server';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  currentArticleId: {
    type: Number,
    default: 0
  }
});




const showModal = ref(false);

const article = ref({
  title: '',
  picture: '',
  content: ''
})

const handleUploadSuccess = (url) => {
  article.value.picture = url;
  alert("上传成功: "+ url);
};

const handleConfirm = async () => {
  if(props.isEdit){//进入编辑
    updataArt();
  }else{//进入创建
    createArt();
  }
};

const createArt = async () => {
  try {
    article.value.content = content.value
    await userCreateArt(server.token, article.value).then((res)=>{
      if(res.data.code == 0 ){
        alert("发布成功: "+res.data.data);
      }else{
        alert("发布失败: "+res.data.msg);
      }
    })
  } catch (error) {
    alert("发布失败"+error);
  } finally {
    emit('save-content', content.value);
    closeModal();
  }
}

const updataArt = async () => {
  const data = {
    id: props.currentArticleId,
    title: article.value.title,
    picture: article.value.picture,
    content: content.value,
  }
  try {
    await userUpdateArt(server.token, data).then((res)=>{
      if(res.data.code == 0 ){
        alert("修改成功: "+res.data.data);
      }else{
        alert("修改失败: "+res.data.msg);
      }
    })
  } catch (error) {
    alert("修改失败"+error);
  } finally {
    emit('save-content', content.value);
    closeModal();
  }
}





const emit = defineEmits(['update:visible', 'save-content']);
const quillEditor = ref(null);
const content = ref(props.initialContent);
const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'script': 'sub' }, { 'script': 'super' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image', 'video']
    ]
  },
  placeholder: '请输入内容...',
  readOnly: false
};

const onEditorReady = (quill) => {
  quill
  const params = {
    articleId: props.currentArticleId
  }
  if(props.isEdit){//进入编辑状态
    articleDetail(server.token, params).then((res)=>{
      if(res.data.code == 0){
        console.log(res.data.data)
        content.value = res.data.data.content
        article.value.content = res.data.data.content
        article.value.picture = res.data.data.picture
        article.value.title = res.data.data.title
      }else{

        alert("文章获取失败："+res.data.msg)

      }
    })
  }else{//进入创建状态
    content.value = '';
    article.value.content = '';
    article.value.picture = '';
    article.value.title = '';
  }
};

const closeModal = () => {
  emit('update:visible', false);
};


// 当initialContent变化时更新编辑器内容
watch(() => props.initialContent, (newVal) => {
  content.value = newVal;
});

// 当visible变为true时，重置编辑器内容
watch(() => props.visible, (newVal) => {
  if (newVal) {
    content.value = props.initialContent;
    if (quillEditor.value) {
      quillEditor.value.setHTML(props.initialContent);
    }
  }
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-width: 90%;
  max-height: 90vh;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header.row {
  justify-content: start;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-content {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.modal-footer {
  padding: 12px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
  border: 1px solid #1890ff;
}

/* 调整Quill编辑器样式 */
:deep(.ql-container) {
  height: 400px;
  font-family: inherit;
}

:deep(.ql-editor) {
  min-height: 300px;
}
</style>
